﻿using GloboTicketAdmin.API.Models;
using SqlSugar;

namespace GloboTicketAdmin.API.Extensions.WebExtensions
{
    public static class SqlSugarExtension
    {
        public static void AddSqlSugar(this IServiceCollection services, IConfiguration configuration)
        {
            // 读取数据库配置
            var dbConfig = new DbConfig();
            configuration.GetSection("ConnectionStrings").Bind(dbConfig);
            dbConfig.DatabaseType = configuration["DatabaseType"];

            // 创建SqlSugar客户端
            var db = new SqlSugarClient(new List<ConnectionConfig>
        {
            new ConnectionConfig
            {
                ConnectionString = GetConnectionString(dbConfig),
                DbType = GetDbType(dbConfig.DatabaseType),
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute ,
                //ConfigureExternalServices = new ConfigureExternalServices
                //{
                //    EntityService = (property, column) =>
                //    {
                //        // 可以配置实体和数据库列的映射关系
                //        if (property.Name == "Id")
                //        {
                //            column.IsPrimarykey = true;
                //            column.IsIdentity = true;
                //        }
                //    }
                //}
            }
        });

            // 注册到依赖注入容器
            services.AddSingleton<ISqlSugarClient>(db);

            // 全局异常处理
            db.Aop.OnError = ex =>
            {
                // 可以记录错误日志
                Console.WriteLine($"SqlSugar Error: {ex.Message}");
            };
        }

        // 根据配置获取连接字符串
        private static string GetConnectionString(DbConfig dbConfig)
        {
            return dbConfig.DatabaseType?.ToLower() switch
            {
                "sqlite" => dbConfig.Sqlite ?? string.Empty,
                "mysql" => dbConfig.MySql ?? string.Empty,
                "postgresql" => dbConfig.PostgreSQL ?? string.Empty,
                "oracle" => dbConfig.Oracle ?? string.Empty,
                _ => dbConfig.SqlServer ?? string.Empty
            };
        }

        // 根据配置获取数据库类型
        private static DbType GetDbType(string? dbType)
        {
            return dbType?.ToLower() switch
            {
                "sqlite" => DbType.Sqlite,
                "mysql" => DbType.MySql,
                "postgresql" => DbType.PostgreSQL,
                "oracle" => DbType.Oracle,
                _ => DbType.SqlServer
            };
        }
    }
}
